package com.opencee.cloud.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.opencee.boot.db.mybatis.service.impl.SupperServiceImpl;
import com.opencee.cloud.base.entity.BaseOrganizationUserEntity;
import com.opencee.cloud.base.mapper.BaseOrganizationUserMapper;
import com.opencee.cloud.base.service.IBaseOrganizationService;
import com.opencee.cloud.base.service.IBaseOrganizationUserService;
import com.opencee.cloud.base.service.IBaseUserService;
import com.opencee.cloud.base.vo.BaseOrganizationUserVO;
import com.opencee.cloud.base.vo.BaseOrganizationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织机构用户 服务实现类
 * </p>
 *
 * @author liuyadu
 * @since 2021-04-16
 */
@Service
public class BaseOrganizationUserServiceImpl extends SupperServiceImpl<BaseOrganizationUserMapper, BaseOrganizationUserEntity> implements IBaseOrganizationUserService {
    @Autowired
    private IBaseOrganizationService organizationService;
    @Autowired
    private IBaseUserService userService;

    /**
     * 查询用户隶属部门
     *
     * @param userId
     * @return
     */
    @Override
    public List<BaseOrganizationVO> listByUserId(Long userId) {
        return baseMapper.selectByUserId(userId);
    }

    /**
     * 查询组织成员列表
     *
     * @param orgId
     * @return
     */
    @Override
    public IPage<BaseOrganizationUserVO> listUsersByOrgId(IPage page, Long orgId) {
        // 查询当前及以下组织
        List<Long> orgIds = organizationService.listSelfWithSubById(orgId).stream().map(t -> t.getId()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(orgIds)) {
            return new Page<>();
        }
        return baseMapper.selectUsersByOrgIds(page, orgIds);
    }

    /**
     * 移除组织成员
     *
     * @param orgId
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeOrgUser(Long orgId, Long userId) {
        QueryWrapper<BaseOrganizationUserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BaseOrganizationUserEntity::getUserId, userId);
        wrapper.lambda().eq(BaseOrganizationUserEntity::getOrgId, orgId);
        // @todo 修改
        return remove(wrapper);
    }

    /**
     * 添加组织成员
     *
     * @param orgId
     * @param userSet
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrgUsers(Long orgId, Set<Long> userSet) {
        List<BaseOrganizationUserEntity> entityList = userSet.stream().filter(t -> {
            return !exists(orgId, t);
        }).map(t -> {
            BaseOrganizationUserEntity entity = new BaseOrganizationUserEntity();
            entity.setOrgId(orgId);
            entity.setUserId(t);
            entity.setDirect(false);
            entity.setLeader(false);
            return entity;
        }).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(entityList)) {
            super.saveBatch(entityList);
        }
    }

    /**
     * 转移机构下的成员
     *
     * @param oldOrgIds
     * @param newOrgId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void moveOrgUser(Set<Long> oldOrgIds, Long newOrgId) {
        if (CollectionUtils.isEmpty(oldOrgIds)) {
            return;
        }
        QueryWrapper<BaseOrganizationUserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(BaseOrganizationUserEntity::getOrgId, oldOrgIds);
        BaseOrganizationUserEntity entity = new BaseOrganizationUserEntity();
        entity.setOrgId(newOrgId);
        update(entity, wrapper);
        // 批量更新用户直属机构
        userService.batchUpdateOrgId(oldOrgIds, newOrgId);
    }

    /**
     * 更新部门负责人
     *
     * @param orgId
     * @param userId
     */
    @Override
    public void updateLeader(Long orgId, Long userId) {
        QueryWrapper<BaseOrganizationUserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BaseOrganizationUserEntity::getOrgId, orgId);
        wrapper.lambda().eq(BaseOrganizationUserEntity::getUserId, userId);
        boolean exists = count(wrapper) > 0;
        BaseOrganizationUserEntity entity = new BaseOrganizationUserEntity();
        if (!exists) {
            // 不存在直接添加
            entity.setOrgId(orgId);
            entity.setUserId(userId);
            entity.setDirect(false);
            entity.setLeader(true);
            this.save(entity);
        } else {
            // 更新
            entity.setLeader(true);
            wrapper.clear();
            wrapper.lambda().eq(BaseOrganizationUserEntity::getOrgId, orgId);
            wrapper.lambda().eq(BaseOrganizationUserEntity::getUserId, userId);
            // 设置部门当前用户为负责人
            this.update(entity, wrapper);
        }
        entity = new BaseOrganizationUserEntity();
        entity.setLeader(false);
        wrapper.clear();
        wrapper.lambda().eq(BaseOrganizationUserEntity::getOrgId, orgId);
        wrapper.lambda().ne(BaseOrganizationUserEntity::getUserId, userId);
        // 取消部门其他用户职位
        this.update(entity, wrapper);
    }

    /**
     * 更新用户直属部门
     *
     * @param orgId
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDirect(Long orgId, Long userId) {
        QueryWrapper<BaseOrganizationUserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BaseOrganizationUserEntity::getUserId, userId);
        wrapper.lambda().eq(BaseOrganizationUserEntity::getDirect, true);
        Boolean exists = count(wrapper) > 0;
        BaseOrganizationUserEntity entity = new BaseOrganizationUserEntity();
        if (!exists) {
            // 不存在直接添加
            entity.setOrgId(orgId);
            entity.setUserId(userId);
            entity.setDirect(true);
            entity.setLeader(false);
            this.save(entity);
            // 更新用户直属部门
            userService.updateOrgId(userId, orgId);
        } else {
            // 更新
            entity.setOrgId(orgId);
            QueryWrapper<BaseOrganizationUserEntity> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(BaseOrganizationUserEntity::getUserId, userId);
            queryWrapper.lambda().eq(BaseOrganizationUserEntity::getDirect, true);
            // 修改用户直属部门
            this.update(entity, queryWrapper);
        }
    }

    /**
     * 检查是否存在
     *
     * @param orgId
     * @param userId
     * @return
     */
    @Override
    public boolean exists(Long orgId, Long userId) {
        QueryWrapper<BaseOrganizationUserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BaseOrganizationUserEntity::getUserId, userId);
        wrapper.lambda().eq(BaseOrganizationUserEntity::getOrgId, orgId);
        return count(wrapper) > 0;
    }

}
